#include "StdAfx.h"
#include "logthread.h"
#include "filelog.h"

CLogThread::CLogThread(void)
{
}

CLogThread::~CLogThread(void)
{
}

bool CLogThread::Start( void )
{
    if (!m_log_data_cache.Init(MAX_LOG_CACHE*2))
    {
        return false;
    }
    m_run = true;
    return CThread::Start(false);
}

void CLogThread::Stop( void )
{
    m_run = false;
    CThread::WaitFor();
}

void CLogThread::ThreadProc( void )
{
    while (m_run)
    {
        log_data_head head;
        while (m_log_data_cache.PopFront((char*)&head, sizeof(head)))
        {
            if (head.log_console)
            {
                switch (head.log_level)
                {
                case LOG_LEVEL_CRI:
                    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED);
                    break;
                case LOG_LEVEL_WRN:
                    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
                    break;
                case LOG_LEVEL_INF:
                    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_GREEN);
                    break;
                case LOG_LEVEL_DBG:
                    break;
                }
            }

            if (m_log_data_cache.PopFront(m_log_buf, head.data_len))
            {
                m_log_buf[head.data_len] = '\0';
                head.log->Write(m_log_buf, head.log_console);
            }

            if (head.log->need_flush())
            {
                head.log->FlushLog();
            }

            if (head.log_console)
            {
                SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
            }
        }
        Sleep(1);
    }
}

bool CLogThread::PushLogData( char* data, int size )
{
    return m_log_data_cache.PushBack(data, size);
}
